package net.zhengxinyun.performance.controller.login;

import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.*;
import net.zhengxinyun.performance.service.indicators.CountryIndicatorsService;
import net.zhengxinyun.performance.service.indicators.CountryUnitIndicatorsService;
import net.zhengxinyun.performance.service.indicators.TownIndicatorsService;
import net.zhengxinyun.performance.service.login.LoginService;
import net.zhengxinyun.performance.service.login.RolePerService;
import net.zhengxinyun.performance.service.login.TokenService;
import net.zhengxinyun.performance.service.login.UserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/userRole")
public class RolePerCtrl  {


    @Autowired
    private RolePerService rolePerService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private LoginService loginService;

    @Autowired
    private TownIndicatorsService townIndicatorsService;

    @Autowired
    private CountryIndicatorsService cityIndexService;

    @Autowired
    private CountryUnitIndicatorsService departIndexSercice;

    @Autowired
    private UserService userService;

    /**
     * 查询用户权限
     * @param
     * @return
     */
    @PostMapping("/query")
    public Result<HashMap<String,Object>> getUserRolePer(@RequestBody RoleParam param, HttpServletRequest request)
    {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {

            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            UserFilter userfilter = new UserFilter();
            userfilter.setId(userEntity.getId());
            List<UserFilter> users = userService.queryUsers(userfilter);

            HashMap<String, Object> map = new HashMap<>();
            //Double pageTotal = 1.0;

            // RolePerFilter filter = new RolePerFilter();
            if(!"admin".equals(userEntity.getUserPermissions()) )
            {
                param.rolePerFilter.setDepartCode(userEntity.getDepartcode());
            }

            List<RolePerFilter> list = rolePerService.query(param.rolePerFilter);
            if (list.size() == 0 && param.rolePerFilter.getPageNumber() != 0) {
                param.rolePerFilter.setPageNumber(param.rolePerFilter.getPageNumber() - 1);
            }
            list = rolePerService.query(param.rolePerFilter);


            //处理勾选状态
            Util.checkItem(list);

            Integer pageTotal = rolePerService.queryForCount(param.rolePerFilter);
            map.put("list", list);
            map.put("pageTotal", pageTotal);

            /**
             * ---可操作性的菜单数量--
             */
            List<MenuLists> listRights = new ArrayList<>();

            RolePerEntity userRole = rolePerService.selectByPrimaryKey(userEntity.getRoleid());
            String strrights ="";
            if (ObjectUtils.isBlank(userRole)) {
                strrights = userEntity.getHaveRight();
            } else {
                 strrights = userRole.getHaveRight();
            }
            if (StringUtils.isNotBlank(strrights)) {
                String[] menus = strrights.split(",");
                for (String code : menus) {
                    MenuLists me = rolePerService.getMenus(code);
                    listRights.add(me);
                }
            }
            map.put("haveRights", listRights);

            /**
             * 获取可操作的指标集合
             */
            /**
             * 超级管理员
             */
            String year = (String) request.getSession().getAttribute("currentYear");
            if(year==null)
            {
                return  ResultUtils.getResults(Result.Status.OVERTIME,"session过期",null);
            }
            if ("admin".equals(userEntity.getUserPermissions())) {

                System.out.println(year);
                TownIndicatorsFilter filter = new TownIndicatorsFilter();
                filter.setDateTime(year);
                filter.setIndexType("二级指标");
                List<TownIndicatorsFilter> listIndexs = townIndicatorsService.query(filter);
                map.put("indexRights", listIndexs);

                /*
                 *市指标
                 */
                CountryIndicatorsFilter cityfiler  = new CountryIndicatorsFilter();
                cityfiler.setPageSize(0);
               // cityfiler.setLeadUnit(userEntity.getDepartcode());
                cityfiler.setDateTime(year);
                List<CountryIndicatorsFilter> cityIndexs  =cityIndexService.query(cityfiler);
                map.put("cityIndex",cityIndexs);

                /*
                    县直单位指标
                 */
                CountryUnitIndicatorsFilter departFilter = new CountryUnitIndicatorsFilter();
                //departFilter.setLeadUnit(userEntity.getDepartcode());
                departFilter.setDateTime(year);
                departFilter.setPageSize(0);
                List<CountryUnitIndicatorsEntity> departIndex  = departIndexSercice.query(departFilter);
                map.put("departIndex",departIndex);

            } else {
                /**
                 * 非超管理员
                 */

                /*
                 *县对乡镇指标
                 */
                TownIndicatorsFilter filter = new TownIndicatorsFilter();
                filter.setPageSize(0);
                filter.setIndexType("二级指标");
                if("县直单位".equals(users.get(0).getDepartType()  )){
                    filter.setLeadUnit(userEntity.getDepartcode());
                }

                filter.setDateTime(year);
                List<TownIndicatorsFilter> listIndex = townIndicatorsService.query(filter);
                map.put("indexRights", listIndex);

                /*
                 *市指标
                 */
                CountryIndicatorsFilter cityfiler  = new CountryIndicatorsFilter();
                cityfiler.setPageSize(0);
                cityfiler.setLeadUnit(userEntity.getDepartcode());
                cityfiler.setDateTime(year);
                List<CountryIndicatorsFilter> cityIndexs  =cityIndexService.query(cityfiler);
                map.put("cityIndex",cityIndexs);

                /*
                    县直单位指标
                 */
                CountryUnitIndicatorsFilter departFilter = new CountryUnitIndicatorsFilter();
                departFilter.setLeadUnit(userEntity.getDepartcode());
                departFilter.setDateTime(year);
                departFilter.setPageSize(0);
                List<CountryUnitIndicatorsEntity> departIndex  = departIndexSercice.query(departFilter);
                map.put("departIndex",departIndex);
            }


            return ResultUtils.getSuccessResults(map);
        }


         return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    //保存
    @PostMapping("/insert")
    public Result<String> insert(@RequestBody RoleParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {

            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);

            /**
             * 菜单权限
             */
            if(ObjectUtils.isNotBlank(param.rolePerEntity.getCheckAllGroup()) )
            {
                List<String> rights  = param.rolePerEntity.getCheckAllGroup();
                String roleRight  = String.join(",",rights);
                param.rolePerEntity.setRoleRight(roleRight);
                /**
                 * 拥有可操作的的菜单
                 */
                param.rolePerEntity.setHaveRight(roleRight);
            }



            /**
             * 按钮权限
             */
            if(ObjectUtils.isNotBlank(param.rolePerEntity.getBtnRights()))
            {
                List<String> btnRights = param.rolePerEntity.getBtnRights();
                String StrBtnRight = String.join(",",btnRights);
                param.rolePerEntity.setBtnRight(StrBtnRight);
            }

            /**
             * 指标权限 县对乡镇
             */
            if(ObjectUtils.isNotBlank(param.rolePerEntity.getCheckAllindexGroup()))
            {
                List<String> indexList = param.rolePerEntity.getCheckAllindexGroup();
                String strIndex  = String.join(",",indexList);
                param.rolePerEntity.setIndexRight(strIndex);

               // param.rolePerEntity.setHaveIndexs(strIndex);
            }
            /*
            市指标
             */
            if(ObjectUtils.isNotBlank(param.rolePerEntity.getCheckCityGroup()))
            {
                List<String> indexList = param.rolePerEntity.getCheckCityGroup();
                String strIndex  = String.join(",",indexList);
                param.rolePerEntity.setCityIndex(strIndex);
            }

            /*
             *单位指标
             */
            if(ObjectUtils.isNotBlank(param.rolePerEntity.getCheckUnitGroup()))
            {
                List<String> indexList = param.rolePerEntity.getCheckUnitGroup();
                String strIndex  = String.join(",",indexList);
                param.rolePerEntity.setDepartIndex(strIndex);
            }

            /**
             * 谁创建，控制查看权限。
             */
            param.rolePerEntity.setCreater(userEntity.getId().toString());
            param.rolePerEntity.setDepartCode(userEntity.getDepartcode());
            param.rolePerEntity.setDel(0);
            param.rolePerEntity.setId(null);//防止程伟节又把主键传进来，造成主键冲突
            rolePerService.insert(param.rolePerEntity);

            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对");
    }
    //修改
    @PostMapping("/update")
    public Result<String> updateRoleRight(@RequestBody RoleParam param)
    {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            //勾选状态的菜单权限值
            String roleRight =null;
            if(ObjectUtils.isNotBlank(param.rolePerEntity.getCheckAllGroup()))
            {
                List<String> rights  = param.rolePerEntity.getCheckAllGroup();
                roleRight= String.join(",",rights);
            }
            param.rolePerEntity.setRoleRight(roleRight);

            //勾选状态的按钮权限值
            String StrBtnRight =null;
            if(ObjectUtils.isNotBlank(param.rolePerEntity.getBtnRights()))
            {
                List<String> btnRights = param.rolePerEntity.getBtnRights();
                StrBtnRight= String.join(",",btnRights);
            }
            param.rolePerEntity.setBtnRight(StrBtnRight);
            /**
             * 指标权限
             */
            String strIndex =null;
            if(ObjectUtils.isNotBlank(param.rolePerEntity.getCheckAllindexGroup()))
            {
                List<String> indexList = param.rolePerEntity.getCheckAllindexGroup();
                strIndex = String.join(",",indexList);

            }
            param.rolePerEntity.setIndexRight(strIndex);

               /*
            市指标
             */
            String cityindex= null;
            if(ObjectUtils.isNotBlank(param.rolePerEntity.getCheckCityGroup()))
            {
                List<String> indexList = param.rolePerEntity.getCheckCityGroup();
                cityindex  = String.join(",",indexList);

            }
            param.rolePerEntity.setCityIndex(cityindex);
            /*
             *单位指标
             */
            String departIndex =null;
            if(ObjectUtils.isNotBlank(param.rolePerEntity.getCheckUnitGroup()))
            {
                List<String> indexList = param.rolePerEntity.getCheckUnitGroup();
                departIndex  = String.join(",",indexList);

            }
            param.rolePerEntity.setDepartIndex(departIndex);




            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
           /**
             * 超级管理员才可以更改 拥有的菜单数 和 指标数
            * */

            if("admin".equals(userEntity.getUserPermissions()))
            {
               // param.rolePerEntity.setHaveIndexs(strIndex);
                param.rolePerEntity.setHaveRight(roleRight); //菜单
            }

           if(1==param.rolePerEntity.getId())
           {
               return  ResultUtils.getResults("500","修改失败，超级管理员权限不可编辑修改");
           }

            rolePerService.updateByPrimaryKeySelective(param.rolePerEntity);


            return ResultUtils.getSuccessResults();
        }
        return  ResultUtils.getResults(Result.Status.OVERTIME, "token不对");

    }


    @PostMapping("/delete")
    public Result<String> delete(@RequestBody RoleParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            if(1==param.rolePerEntity.getId())
            {
                return  ResultUtils.getResults("500","修改失败，超级管理员权限不可删除");
            }
            rolePerService.deleteByPrimaryKey(param.rolePerEntity.getId());
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对");
    }



}
class RoleParam{
    public TokenEntity tokenEntity;
    public RolePerEntity rolePerEntity;
    public RolePerFilter rolePerFilter;
}